package com.nsgf.library.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.netease.neliveplayer.playerkit.core.view.BaseSurfaceView;
import com.netease.neliveplayer.playerkit.sdk.LivePlayer;
import com.netease.neliveplayer.playerkit.sdk.LivePlayerObserver;
import com.netease.neliveplayer.playerkit.sdk.PlayerManager;
import com.netease.neliveplayer.playerkit.sdk.extension.SimpleLivePlayerObserver;
import com.netease.neliveplayer.playerkit.sdk.model.MediaInfo;
import com.netease.neliveplayer.playerkit.sdk.model.SDKOptions;
import com.netease.neliveplayer.playerkit.sdk.model.StateInfo;
import com.netease.neliveplayer.playerkit.sdk.model.VideoBufferStrategy;
import com.netease.neliveplayer.playerkit.sdk.model.VideoOptions;
import com.netease.neliveplayer.playerkit.sdk.model.VideoScaleMode;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;

/**
 * 网易云信直播播放器Activity
 * 基于playerkit模块实现
 * 
 * 使用示例：
 * Intent intent = new Intent(this, LiveBroadcastActivity.class);
 * startActivity(intent);
 * 
 * 功能特性：
 * 1. 支持RTMP、HLS、HTTP-FLV等主流直播协议
 * 2. 硬件解码，性能优异
 * 3. 自动重试机制
 * 4. 实时状态监控
 * 5. 播放控制（播放、暂停、停止）
 * 6. 自定义流地址输入
 */
public class LiveBroadcastActivity extends BaseActivity {

    private static final String TAG = "LiveBroadcastActivity";

    protected StateHolder mStates;
    private LivePlayer mLivePlayer;
    private BaseSurfaceView mLivePlayerView;
    private TextView mStatusText;
    private Button mBtnPlay, mBtnPause, mBtnStop, mBtnStartStream;
    private EditText mEtStreamUrl;
    private boolean mIsPlaying = false;
    
    private static final int PERMISSION_REQUEST_CODE = 1001;
    private static final String[] REQUIRED_PERMISSIONS = {
        Manifest.permission.INTERNET,
        Manifest.permission.ACCESS_NETWORK_STATE
    };

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(StateHolder.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_live_broadcast, BR.vm, mStates);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {
            Log.d(TAG, "onCreate开始");
            
            // 初始化PlayerManager
            initPlayerManager();
            
            // 检查权限
            if (!checkPermissions()) {
                requestPermissions();
            }
            
            initViews();
            setupListeners();
            setDefaultTestStream();
            
            Log.d(TAG, "onCreate完成");
        } catch (Exception e) {
            Log.e(TAG, "onCreate failed", e);
            Toast.makeText(this, "Activity初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 初始化PlayerManager
     */
    private void initPlayerManager() {
        try {
            Log.d(TAG, "初始化PlayerManager");
            
            // 创建SDK配置
            SDKOptions sdkOptions = new SDKOptions();
            sdkOptions.thirdUserId = "live_broadcast_user"; // 用户标识
            sdkOptions.refreshPreLoadDuration = 30 * 60 * 1000; // 30分钟刷新间隔
            sdkOptions.isCloseTimeOutProtect = false; // 开启超时保护
            
            // 初始化PlayerManager
            PlayerManager.init(this, sdkOptions);
            
            Log.d(TAG, "PlayerManager初始化完成");
            
        } catch (Exception e) {
            Log.e(TAG, "PlayerManager初始化失败", e);
            Toast.makeText(this, "播放器初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    private void initViews() {
        Log.d(TAG, "开始初始化视图");
        
        mLivePlayerView = findViewById(R.id.live_player_view);
        Log.d(TAG, "mLivePlayerView: " + mLivePlayerView);
        
        mStatusText = findViewById(R.id.status_text);
        mBtnPlay = findViewById(R.id.btn_play);
        mBtnPause = findViewById(R.id.btn_pause);
        mBtnStop = findViewById(R.id.btn_stop);
        mBtnStartStream = findViewById(R.id.btn_start_stream);
        mEtStreamUrl = findViewById(R.id.et_stream_url);
    }
    
    private void setupListeners() {
        mBtnPlay.setOnClickListener(v -> playStream());
        mBtnStop.setOnClickListener(v -> stopStream());
        mBtnStartStream.setOnClickListener(v -> startStream());
    }
    
    private void startStream() {
        Log.d(TAG, "开始启动流播放");
        
        if (mEtStreamUrl == null) {
            Log.e(TAG, "mEtStreamUrl is null");
            return;
        }
        
        String streamUrl = mEtStreamUrl.getText().toString().trim();
        if (streamUrl.isEmpty()) {
            Toast.makeText(this, "请输入直播流地址", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Log.d(TAG, "流地址: " + streamUrl);
        
        try {
            if (mStatusText != null) {
                mStatusText.setText("开始加载流...");
            }
            
            // 创建播放器配置
            VideoOptions options = new VideoOptions();
            options.bufferStrategy = VideoBufferStrategy.FAST; // 极速模式
            options.hardwareDecode = true; // 启用硬件解码
            options.isAutoStart = false; // 不自动播放
            options.playbackTimeout = 10; // 10秒超时
            
            // 创建播放器
            mLivePlayer = PlayerManager.buildLivePlayer(this, streamUrl, options);
            
            // 设置渲染视图
            mLivePlayer.setupRenderView(mLivePlayerView, VideoScaleMode.FIT);
            
            // 注册观察者
            mLivePlayer.registerPlayerObserver(mPlayerObserver, true);
            
            // 开始播放
            mLivePlayer.start();
            
        } catch (Exception e) {
            Log.e(TAG, "加载流失败", e);
            if (mStatusText != null) {
                mStatusText.setText("加载流失败: " + e.getMessage());
            }
            Toast.makeText(this, "加载流失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    private void playStream() {
        try {
            if (mLivePlayer != null) {
                mLivePlayer.start();
                mIsPlaying = true;
                if (mStatusText != null) {
                    mStatusText.setText("播放中");
                }
                updateButtonStates(false, true, true);
            }
        } catch (Exception e) {
            Toast.makeText(this, "播放失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    

    private void stopStream() {
        try {
            if (mLivePlayer != null) {
                mLivePlayer.stop();
                mIsPlaying = false;
                if (mStatusText != null) {
                    mStatusText.setText("已停止");
                }
                updateButtonStates(true, false, false);
            }
        } catch (Exception e) {
            Toast.makeText(this, "停止失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void updateButtonStates(boolean playEnabled, boolean pauseEnabled, boolean stopEnabled) {
        if (mBtnPlay != null) {
            mBtnPlay.setEnabled(playEnabled);
        }
        if (mBtnPause != null) {
            mBtnPause.setEnabled(pauseEnabled);
        }
        if (mBtnStop != null) {
            mBtnStop.setEnabled(stopEnabled);
        }
    }
    
    private boolean checkPermissions() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) 
                != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    
    private void requestPermissions() {
        ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE);
    }
    
    /**
     * 测试播放器功能
     */
    public void testPlayer() {
        Log.d(TAG, "测试播放器状态");
        Log.d(TAG, "mLivePlayer: " + mLivePlayer);
        Log.d(TAG, "mLivePlayerView: " + mLivePlayerView);
        
        if (mLivePlayer != null) {
            Toast.makeText(this, "播放器已初始化", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "播放器已初始化");
        } else {
            Toast.makeText(this, "播放器未初始化", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "播放器未初始化");
        }
        
        // 测试流地址
        String testUrl = "rtmp://live-push.bilivideo.com/live-bvc/?streamname=test&key=test";
        if (mEtStreamUrl != null) {
            mEtStreamUrl.setText(testUrl);
        }
    }
    
    /**
     * 设置默认测试流
     */
    private void setDefaultTestStream() {
        if (mEtStreamUrl == null) {
            return;
        }
        
        // 检查是否有从Intent传递过来的流地址
        String streamUrl = getIntent().getStringExtra("stream_url");
        if (streamUrl != null && !streamUrl.isEmpty()) {
            mEtStreamUrl.setText(streamUrl);
        } else {
            // 使用默认测试流
            String defaultUrl = "rtmp://live-push.bilivideo.com/live-bvc/?streamname=live_1234567890&key=1234567890";
            mEtStreamUrl.setText(defaultUrl);
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if (mLivePlayer != null) {
            mLivePlayer.onActivityResume(true);
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if (mLivePlayer != null) {
            mLivePlayer.onActivityStop(true);
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLivePlayer != null) {
            mLivePlayer.registerPlayerObserver(mPlayerObserver, false);
            mLivePlayer.stop();
            mLivePlayer = null;
        }
        // 清空引用
        mLivePlayerView = null;
        mStatusText = null;
        mBtnPlay = null;
        mBtnPause = null;
        mBtnStop = null;
        mBtnStartStream = null;
        mEtStreamUrl = null;
    }
    
    /**
     * 播放器观察者
     */
    private final LivePlayerObserver mPlayerObserver = new SimpleLivePlayerObserver() {
        @Override
        public void onPreparing() {
            Log.d(TAG, "播放器准备中");
            runOnUiThread(() -> {
                if (mStatusText != null) {
                    mStatusText.setText("准备中...");
                }
            });
        }
        
        @Override
        public void onPrepared(MediaInfo mediaInfo) {
            Log.d(TAG, "播放器准备完成: " + mediaInfo);
            runOnUiThread(() -> {
                if (mStatusText != null) {
                    mStatusText.setText("准备完成");
                }
                updateButtonStates(true, false, true);
            });
        }
        
        @Override
        public void onError(int code, int extra) {
            Log.e(TAG, "播放器错误: code=" + code + ", extra=" + extra);
            runOnUiThread(() -> {
                String errorMsg = "播放错误: " + code + ", " + extra;
                if (mStatusText != null) {
                    mStatusText.setText(errorMsg);
                }
                Toast.makeText(LiveBroadcastActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                updateButtonStates(true, false, false);
                mIsPlaying = false;
            });
        }
        
        @Override
        public void onFirstVideoRendered() {
            Log.d(TAG, "第一帧视频渲染");
            runOnUiThread(() -> {
                if (mStatusText != null) {
                    mStatusText.setText("视频播放中");
                }
                updateButtonStates(false, true, true);
                mIsPlaying = true;
            });
        }
        
        @Override
        public void onFirstAudioRendered() {
            Log.d(TAG, "第一帧音频渲染");
        }
        
        @Override
        public void onBufferingStart() {
            Log.d(TAG, "开始缓冲");
            runOnUiThread(() -> {
                if (mStatusText != null) {
                    mStatusText.setText("缓冲中...");
                }
            });
        }
        
        @Override
        public void onBufferingEnd() {
            Log.d(TAG, "缓冲完成");
            runOnUiThread(() -> {
                if (mStatusText != null && mIsPlaying) {
                    mStatusText.setText("播放中");
                }
            });
        }
        
        @Override
        public void onBuffering(int percent) {
            Log.d(TAG, "缓冲进度: " + percent + "%");
            runOnUiThread(() -> {
                if (mStatusText != null && percent < 100) {
                    mStatusText.setText("缓冲中: " + percent + "%");
                }
            });
        }
        
        @Override
        public void onVideoDecoderOpen(int value) {
            Log.d(TAG, "视频解码器开启: " + value);
            runOnUiThread(() -> {
                if (mStatusText != null) {
                    mStatusText.setText("解码器: " + (value == 1 ? "硬件" : "软件"));
                }
            });
        }
        
        @Override
        public void onStateChanged(StateInfo stateInfo) {
            Log.d(TAG, "播放器状态变化: " + stateInfo);
            runOnUiThread(() -> {
                if (mStatusText != null) {
                    mStatusText.setText("状态: " + stateInfo.getState());
                }
            });
        }
        
        @Override
        public void onHttpResponseInfo(int code, String header) {
            Log.d(TAG, "HTTP响应信息: code=" + code + ", header=" + header);
        }
    };
}
